package com.yangchao.webflux.exception;


import org.slf4j.Logger;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-2)
@Component
public class GlobalErrorHandler implements ErrorWebExceptionHandler {

    Logger log = org.slf4j.LoggerFactory.getLogger(GlobalErrorHandler.class);
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        // Handle exception and create response
        log.info("GlobalErrorHandler {}",exchange.getRequest().getURI());
        HttpStatus httpStatus = determineHttpStatus(ex);
        return handleErrorResponse(exchange, httpStatus, ex);
    }

    private HttpStatus determineHttpStatus(Throwable ex) {
        // Logic to determine HTTP status based on exception
        return HttpStatus.INTERNAL_SERVER_ERROR; // Example
    }

    private Mono<Void> handleErrorResponse(ServerWebExchange exchange, HttpStatus httpStatus, Throwable ex) {
        // Logic to create and return error response
        exchange.getResponse().setStatusCode(httpStatus);

        return exchange.getResponse().setComplete(); // Example
    }
}